package com.online.olsrootserver.handler;

import com.online.olsrootserver.builder.TextBuilder;
import com.online.olsrootserver.service.CompanyService;
import com.online.olsrootserver.service.CustomerChatServer;
import com.online.olsrootserver.service.FindAentServer;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by littleheng on 2018/4/25
 */
@Component
public class MsgHandler extends AbstractHandler {

    @Autowired
    private CustomerChatServer customerChatServer;

    @Autowired
    private FindAentServer sessionManageCluster;

    @Autowired
    private CompanyService companyService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {

        String content = "";

        try {
            //  获取微信用户基本信息
            String openId = wxMpXmlMessage.getFromUser();
            String companyOpenId = wxMpXmlMessage.getToUser();
            WxMpUser userWxInfo = wxMpService.getUserService()
                    .userInfo(openId, "zh_CN");
            String companyId = this.companyService.getIdByWxNumber(companyOpenId);
            String address = userWxInfo.getCountry() + userWxInfo.getProvince() + userWxInfo.getCity();

            Map<String, Object> redisParams = new HashMap<>();
            redisParams.put("open_id", openId);
            //  查询微信用户在redis中是否存在
            Map redisResult = this.sessionManageCluster.getWeChatUser(redisParams);
            System.out.println(redisResult);

            //  不存在就新增到redis
            if (Integer.parseInt(redisResult.get("result").toString()) == 0) {
                System.out.println("不存在就新增到redis");
                Map<String, Object> saveRedisParamsMap = new HashMap<>();
                saveRedisParamsMap.put("open_id", openId);
                saveRedisParamsMap.put("name", userWxInfo.getNickname());
                saveRedisParamsMap.put("address", address);
                saveRedisParamsMap.put("e_id", Integer.parseInt(companyId));
                saveRedisParamsMap.put("sex", userWxInfo.getSexDesc());

                Map result = this.sessionManageCluster.saveWeChatUser(saveRedisParamsMap);

                System.out.println("新增用户信息到redis成功");
                if (Integer.parseInt(result.get("result").toString()) == 0) {
                    this.logger.info("新增用户信息到redis成功");
                } else {
                    this.logger.info("参数异常");
                }
            }

            Map<String, Object> params = new HashMap<>();
            //  顾客发送文字信息
            if (wxMpXmlMessage.getMsgType().equals(WxConsts.XmlMsgType.TEXT)) {
                params.put("open_id", openId);
                params.put("nick_name", userWxInfo.getNickname());
                params.put("create_time", System.currentTimeMillis());
                params.put("content", wxMpXmlMessage.getContent());
                params.put("msg_id", wxMpXmlMessage.getMsgId());
                params.put("e_id", Integer.parseInt(companyId));

                Map result = this.customerChatServer.textMessageServer(params);

                System.out.println(result);
                if (Integer.parseInt(result.get("type").toString()) == 1) { //  当前客服在忙
                    content = "请稍等片刻...";
                }
            } else if (wxMpXmlMessage.getMsgType().equals(WxConsts.XmlMsgType.IMAGE)) {
                //  顾客发送图片信息
                params.put("open_id", openId);
                params.put("nick_name", userWxInfo.getNickname());
                params.put("create_time", System.currentTimeMillis());
                params.put("pic_url", wxMpXmlMessage.getPicUrl());
                params.put("media_id", wxMpXmlMessage.getMediaId());
                params.put("msg_id", wxMpXmlMessage.getMsgId());
                params.put("e_id", Integer.parseInt(companyId));

                Map result = this.customerChatServer.imgMessageServer(params);
                System.out.println("result。。:"+result);
                if (Integer.parseInt(result.get("type").toString()) == 1) {
                    content = "请稍等片刻...";
                }
            }
        } catch (Exception e) {
            this.logger.info(e.getMessage(), e);
        } finally {
            if ("".equals(content)) {
                return null;
            } else {
                return new TextBuilder().build(content, wxMpXmlMessage, wxMpService);
            }
        }
    }
}